﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Common;
using Aioms.Models;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace Aioms.Controllers
{
    /// <summary>
    /// 巡检点
    /// </summary>
    [DynamicApiController]
    public class InspectionPointController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public InspectionPointController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 巡检点列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] long ilid, [FromForm] string content)
        {
            List<InspectionPoint> inspectionpoints = await db.Queryable<InspectionPoint>()
                .Where(il => il.IsDel == 0)
                .Where(ip => ip.Eid == eid)
                .WhereIF(ilid != 0, ip => ip.Ilid == ilid)
                .WhereIF(!string.IsNullOrEmpty(content), ip => ip.Name.Contains(content))
                .ToListAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = inspectionpoints,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加巡检点
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="inspectionPoint"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] InspectionPoint inspectionPoint)
        {
            long id = await db.Insertable<InspectionPoint>(inspectionPoint).ExecuteReturnBigIdentityAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = id,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除巡检点
        /// </summary>
        /// <param name="eid">企业ID</param>
        /// <param name="id">ID</param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id) {
            // 第一步：删除巡检点
            await db.Updateable<InspectionPoint>().SetColumns(ip => ip.IsDel == 1).Where(ip => ip.Eid == eid && ip.Id == id).ExecuteCommandAsync();
            // 第二步：删除巡检项
            await db.Deleteable<InspectionOption>().Where(io => io.Eid == eid && io.Ipid == id).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = "删除巡检点成功",
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改巡检点
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="inspectionPoint"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] InspectionPoint inspectionPoint)
        {
            await db.Updateable<InspectionPoint>(inspectionPoint).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 添加巡检点
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="ipid"></param>
        /// <param name="dvids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostAdddevices([FromForm] long eid, [FromForm] long id, [FromForm] string dvids)
        {
            await db.Updateable<InspectionPoint>().SetColumns(ip => ip.Dvids == dvids).Where(ip => ip.Eid == eid && ip.Id == id).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 获取设备
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            InspectionPoint inspectionpoint = await db.Queryable<InspectionPoint>().Where(ip => ip.Eid == eid && ip.Id == id).SingleAsync();
            List<Device> devices = null;
            if (!string.IsNullOrEmpty(inspectionpoint.Dvids)) {
                List<long> dvids = JArray.Parse(inspectionpoint.Dvids).ToObject<List<long>>();
                devices = await db.Queryable<Device>().Where(dv => dvids.Contains(dv.Id)).ToListAsync();
            }
            UnifyContext.Fill(new { Devices = devices });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = inspectionpoint,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 获取工单冗余巡检点下设备列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="ipid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostRyShow([FromForm] long eid, [FromForm] long woid, [FromForm] long ipid, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            TpWorkOrder workOrders = await db.Queryable<TpWorkOrder>()
                .Where(wo => wo.Eid == eid && wo.Id == woid)
                .SingleAsync();
            XunJianPlan xunjianPlan = workOrders.TaskInfo.ToObject<XunJianPlan>();
            var data = xunjianPlan.XunJianDians.Where(xjd => xjd.Id == ipid).Select(xjd => xjd.XunJianDevices).ToList().FirstOrDefault().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            UnifyContext.Fill(new { Total = data?.Count });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
